from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serialziers.orders import OrderSerializer
from meiduo_admin.utils.page import PageNum
from orders.models import OrderGoods, OrderInfo


class OrdersView(ReadOnlyModelViewSet):
    permission_classes = [IsAdminUser, ]
    # 查询集
    queryset = OrderInfo.objects.all()

    serializer_class = OrderSerializer

    pagination_class = PageNum

    # 重写get_queryset方法，根据前端是否传递keyword值返回不同查询结果
    def get_queryset(self):
        # 获取前端传递的keyword值
        keyword = self.request.query_params.get('keyword')
        # 如果keyword是空字符，则说明要获取所有用户数据
        if keyword is '' or keyword is None:
            return OrderInfo.objects.all()
        else:
            # like=username__contains
            return OrderInfo.objects.filter(order_id__contains=keyword)

    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        修改订单状态
        :param request:
        :param pk 条件
        :return:
        """
        # 通过条件查询订单

        try:
            order = OrderInfo.objects.get(order_id=pk)
        except:
            return Response({'error': '订单编号错误'})

        # 获取订单状态
        status = request.data.get('status')
        if status is None:
            return Response({'error': '缺少状态值'})
        order.status = status
        order.save()

        # 返回结果
        return Response({
            'order_id': pk,
            'status': status
        })
